package cn.chencq.proxy.timer.handler;

import java.net.Proxy;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.chencq.proxy.util.Util;

public class ProxyHandlerEng {

	private static final Logger LOGGER = LoggerFactory.getLogger(ProxyHandlerEng.class);

	private static ProxyHandlerEng proxyHandlerEng = new ProxyHandlerEng();

	private Map<String, GeneralProxyHandler> handlerMap = new HashMap<String, GeneralProxyHandler>();

	public static ProxyHandlerEng getInstance() {
		return proxyHandlerEng;
	}

	private ProxyHandlerEng() {
		init();
	}

	public void init() {
		String pack = "cn.chencq.proxy.timer.handler.custom";
		Set<Class<?>> claList = Util.getClasses(pack);
		try {
			for (Class<?> cla : claList) {
				if (cla.isInterface()) {
					continue;
				}
				if (cla.isAnnotation()) {
					continue;
				}
				if (cla.isEnum()) {
					continue;
				}
				if (Util.isAbstract(cla)) {
					continue;
				}

				// 判断一个类Class1和另一个类Class2是否相同或是另一个类的子类或接口
				if (GeneralProxyHandler.class.isAssignableFrom(cla)) {
					GeneralProxyHandler handler = (GeneralProxyHandler) cla.newInstance();
					if (handlerMap.containsKey(handler.getHandler())) {
						continue;
					} else {
						handlerMap.put(handler.getHandler(), handler);
					}
				}
			}
		} catch (Exception e) {
		}
	}

	public int crawler(String rid, String url, String handler) {
		LOGGER.info("rid:{},crawler,url:{},handler:{}", rid, url, handler);
		GeneralProxyHandler proxyHandler = null;
		if (handler != null) {
			proxyHandler = handlerMap.get(handler);
		} else {
			proxyHandler = new GeneralProxyHandler();
		}

		Proxy proxy = Util.getProxy();
		LOGGER.info("rid:{},crawler, proxy is null:{}", rid, proxy == null);

		return proxyHandler.crawler(rid, url, proxy);
	}
}
